package com.inphase.myfood.dao.base;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.inphase.myfood.util.StringUtils;

public class BaseDaoImpl<T extends Serializable, PK extends Serializable>
		implements BaseDao<T, PK> {
	@Resource(name = "hibernateTemplate")
	private HibernateTemplate hibernateTemplate;
	private Class<T> entityClass;
	private String classStr;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public BaseDaoImpl() {
		this.entityClass = GenericsUtils.getSuperClassGenricType(getClass());
		classStr = StringUtils.removeClassFromStr(entityClass.toString());
	}

	public T getObjectByPK(PK pk) {
		return (T) hibernateTemplate.get(entityClass, pk);
	}

	public List<T> getListObjects() {
		String hql = "from " + classStr;
		return hibernateTemplate.find(hql);
	}

	public List<T> getObjectByParams(String[] params, Object... objects) {
		String hql = "from " + classStr + " t where t.";
		for (int i = 0; i < params.length; i++) {
			if (i == 0) {
				hql = hql + params[i] + " = ?";
			} else {
				hql = hql + " and " + params[i] + " = ?";
			}
		}
		return hibernateTemplate.find(hql, objects);
	}

}
